<template>
<el-row :gutter="20">
    <el-col :span="12">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <el-row>
                        <el-col :span="4" class="detail_img_box">
                            <img :src="dataObj.icon" class="detail_img"
                            style="vertical-align: center;"/>
                        </el-col>
                        <el-col :span="20"
                        style="margin-top: 15px;font-weight: bold; font-size: 20px;">
                            {{ dataObj.name }}
                        </el-col>
                    </el-row>
                </div>
            </template>
            <div class="detail_tag_box ai_box">
                <div class="detail_tag borRadius">
                    收费标准：
                    {{ dataObj.score }}
                    积分/次
                </div>
                <div class="detail_desc_box borRadius">
                    说明：<br/>
                    {{ dataObj.desc }}
                </div>
                <div class="detail_title_box">
                    <span>
                        文案标题
                    </span>
                    <div class="detail_title borRadius clearfix">
                        <el-input class="detail_title_input" 
                            v-model="commitObj.title" 
                            maxlength="100"
                            placeholder="键入文案标题"
                            show-word-limit
                            type="text"
                        />
                    </div>
                </div>
                <div >
                    <span> <!-- curObj.options" -->
                        角色设定
                    </span>
                    <div class="detail_title borRadius clearfix" style="padding-left: 20px;">
                        <checkbox-group  v-model="commitObj.role" >
                            <el-checkbox v-for="it in curObj.options"
                            :label="it" size="large" >
                            {{ it }}
                            </el-checkbox>
                            <br v-if="i % 3 == 1"/>
                        </checkbox-group>
                    </div>
                </div>
                
                <div class="detail_title_box">
                    
                    <span>
                        字数设定
                    </span>
                    <div class="detail_title  clearfix" >
                        <el-row class="borRadius fl"  style="width: 153px">
                            <el-col :span="18">
                                <el-input-number 
                                v-model="commitObj.tokens" 
                                :min="0" 
                                :max="10000"/>
                            </el-col>
                            <el-col :span="6">
                            </el-col>
                        </el-row>
                    </div>
                </div>
                
                <div class="detail_title_box">
                    <span>
                        魔法设定(Prompt)
                    </span>
                    <div class="detail_title borRadius clearfix">
                        <el-input class="detail_title_input" 
                            v-model="commitObj.settings" 
                            maxlength="200"
                            placeholder="键入自定义Prompt(可选)"
                            show-word-limit
                            type="text"
                        />
                    </div>
                </div>

                <div class="detail_bg_box">
                    <span>
                        文案背景
                    </span>
                    <div class="detail_bg borRadius"
                    style="margin-top: 10px;">
                        <el-input 
                            v-model="commitObj.background" 
                            maxlength="5000"
                            placeholder="键入文案背景"
                            show-word-limit
                            type="textarea"
                            :rows="10"
                        />
                    </div>
                </div>
                <div class="detail_btn_box">
                    <el-button 
                    class="fr detail_btn"
                     type="primary"
                     @click="createTaskFun">
                        运行
                    </el-button>
                </div>
            </div>
        </el-card>
    </el-col>

    <el-col :span="12">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    AI智能书写
                </div>
            </template>
            <div class="ai_box" style="white-space: pre-wrap;" >
                {{ showText }}
            </div>
        </el-card>
           
    </el-col>
</el-row>


</template>

<script setup>
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { computed, onMounted, ref, watch} from "vue";
import {useStore} from 'vuex';


let showText = ref('');
const commitObj = ref({
    title: '',
    role: [],
    tokens: 10,
    settings: '',
    background: ''
})
const dataObj = ref({
       id:'',
      icon:"http://47.94.130.238/images/check-original.png",
      name:'',
      desc:'',
      level:'',
      score:0,
      type:'',
      params: []
});
const route = useRoute()
const router = useRouter()
const store = useStore()
let curObj = ref({
    options: '',
    num: ''
});

watch(store.state.curSelPos,(newValue,oldValue)=>{
  if(newValue){
    console.log(`我侦听到了count状态的变化，当前值为${newValue},从而处理相关逻辑`);
  }
  let {searchContent, workList, curSelPos} = store.state;
    let pos = 0;
    for (let i = 0; i < searchContent.length; i++) {
        if (searchContent[i].id == workList[curSelPos]) {
            pos = i;
            break;
        }
    }
    console.log('ttt', searchContent[pos]);
    let tobj = searchContent[pos];
    dataObj.value.id = tobj.id
    dataObj.value.icon = tobj.icon
    dataObj.value.name = tobj.name
    dataObj.value.desc = tobj.desc
    dataObj.value.level = tobj.level
    dataObj.value.score = tobj.score
    dataObj.value.type = tobj.type
    if (!tobj.params) {
        console.log('params为空');
        return
    }
    for (let i = 0;i < tobj.params.length; i++) {
        let it = tobj.params[i];
        dataObj.value.params.push(it)
    }
    try{
        for (let i = 0; i < dataObj.value.params.length; i++) {
            let tobj = dataObj.value.params[i];
            switch (tobj.key){
                case 'role':{
                    curObj.value.options = tobj.options;
                }
                break;
                case 'tokens':{
                    commitObj.value.tokens = tobj.number;
                    console.log('set 字数', tobj.number);
                }
                break;
            }
        }
    }catch(err) {
        console.log('出错了 deatailpage里面', err);
        ElMessage.error('出错了')
    }
})
onMounted(()=> {
    let {searchContent, workList, curSelPos} = store.state;
    let pos = 0;
    for (let i = 0; i < searchContent.length; i++) {
        if (searchContent[i].id == workList[curSelPos]) {
            pos = i;
            break;
        }
    }
    console.log('ttt', searchContent[pos]);
    let tobj = searchContent[pos];
    dataObj.value.id = tobj.id
    dataObj.value.icon = tobj.icon
    dataObj.value.name = tobj.name
    dataObj.value.desc = tobj.desc
    dataObj.value.level = tobj.level
    dataObj.value.score = tobj.score
    dataObj.value.type = tobj.type
    if (!tobj.params) {
        console.log('params为空');
        return
    }
    for (let i = 0;i < tobj.params.length; i++) {
        let it = tobj.params[i];
        dataObj.value.params.push(it)
    }
    // searchContent[workList[curSelPos]].params
    try{
        for (let i = 0; i < dataObj.value.params.length; i++) {
            let tobj = dataObj.value.params[i];
            switch (tobj.key){
                case 'role':{
                    curObj.value.options = tobj.options;
                }
                break;
                case 'tokens':{
                    commitObj.value.tokens = tobj.number;
                    console.log('set 字数', tobj.number);
                }
                break;
            }
        }
    }catch(err) {
        console.log('出错了 deatailpage里面', err);
        ElMessage.error('出错了')
    }
    
})
const isNull = (data) => {
    return data == null || data == '' || data == 0;
}

// console.log('dataobj', dataObj.value);
const createTaskFun = () => {
    // let res = createTask(store.state.curUser.token, 
    // {
    //     module_id: store.state.searchContent[route.query.pos].id, 
    //     params: commitObj
    // });
    // res.then((rData) => {
    //     console.log("rdata", rData);
    //     if (rData.data.code == 200) {
    //         ElMessage({
    //             message: '创建成功',
    //             type: 'success',
    //         })
    //         router.push({path: '/Search/All'})
    //     }else {
    //         ElMessage.error('创建失败')
    //     }

    // }).catch((e)=> {
    //     console.log("出错了" + e);
    // })

    // 创建一个包含数据的可读流对象
    // title: commitObj.value.title,
    //     role: commitObj.value.role,
    //     tokens: commitObj.value.tokens,
    //     settings: commitObj.value.settings,
    //     background: commitObj.value.background
if (
    isNull(commitObj.value.title) ||
    isNull(commitObj.value.role) ||
    isNull(commitObj.value.tokens) ||
    isNull(commitObj.value.settings) ||
    isNull(commitObj.value.background)
) {
    ElMessage.error('数据不能为空')
}

const data = new ReadableStream({
  start(controller) {
    const chunks = ['chunk1', 'chunk2', 'chunk3'];
    chunks.forEach(chunk => {
      controller.enqueue(chunk);
    });
    controller.close();
  }
});

// 设置请求头和请求体
const headers = new Headers();
headers.append('Authorization', 'Bearer ' + store.state.curUser.token);
let {searchContent, workList, curSelPos} = store.state;
let pos = 0;
for (let i = 0; i < searchContent.length; i++) {
    if (searchContent[i].id == workList[curSelPos]) {
        pos = i;
        break;
    }
}
const options = {
  method: 'POST',
  headers: headers,
  body: JSON.stringify({
    module_id: store.state.searchContent[pos].id, 
    params: {
        title: commitObj.value.title,
        role: commitObj.value.role,
        tokens: commitObj.value.tokens,
        settings: commitObj.value.settings,
        background: commitObj.value.background
    },
    stream: true
  })
};

// 发送请求
fetch('http://47.94.130.238/api/v1/job/generate', options)
.then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.body;
  }).then(body => {
//    disableLoading();
    console.log('options=', options);
    showText.value = ''
    const reader = body.getReader();
    function read() {
      return reader.read().then(({ done, value }) => {
        if (done) {
          console.log('已传输完毕');
          return;
        }
        let binaryData = new Uint8Array(value); // 例如，这是一些二进制数据
        let textDecoder = new TextDecoder(); // 创建一个 TextDecoder 对象
        let string = textDecoder.decode(binaryData); // 使用 TextDecoder 对象将二进制数据转换为字符串
        let strings = string.split('data: ');
        for (let i = 0; i < strings.length; i++) {
            let string = strings[i];
            try {
                let obj = JSON.parse(string)
                showText.value += obj.content
                console.log('收到的数据:--'+ obj.content + "--");
            }catch(err){
                console.log('出错啦，收到的数据:--'+ string + "--", err);
            };
        }
        
        read();
      });
    }
    read();
    ElMessage({
        message: '创建成功',
        type: 'success',
    })
    // clearFormData()
  }).catch(error => {
    ElMessage.error('创建失败')
    console.error('Fetch error:', error);
  });
}
const clearFormData = () => {
    commitObj.value.title = ''
    commitObj.value.role = '农业专家'
    commitObj.value.tokens = 1
    commitObj.value.settings = ''
    commitObj.value.background = ''
}
</script>

<style scoped>
.detail_tag_box> div{
    margin-bottom: 20px;
}
.detail_tag {
    margin: 0;
    background-color: green;
    color: white;
    border-radius: 10px;
    width: 200px;
    height: 45px;
    line-height: 45px;
    text-align: center;
}
.borRadius {
    border: 1px solid black;
    border-radius: 10px;
}
.detail_title_box {
    height: 60px;
}
.detail_title{
    position: relative;
    margin-top: 10px;
}
.detail_title_input, .detail_title_tip{
    position: absolute;
}
.detail_title_tip{
    right: 5px;
    top: 5px;
}
.detail_desc {
    background-color: aliceblue;
}
.detail_img {
    width: 50px;
    height: 50px;
}
.detail_desc_box{
    padding: 10px;
    background-color: beige;
}
.detail_btn {
    margin-bottom: 20px;
}
.ai_box{
    height: 500px;
    margin-bottom: 20px;
    overflow-y: auto;  /* 显示垂直方向滚动条 */
}
</style>